<template>
  <div class="user-managee">
    <div class="query-from">
       <el-form :inline="true" class="demo-form-inline" ref="searchForm" :model="table">
   <el-form-item label="部门名"  label-width="100px" prop="deptName" >
      <el-input v-model="table.deptName" autocomplete="false" @keyup.enter="getDeptData"/>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="getDeptData" v-has="'dept-query'">查询</el-button>
       <el-button  @click="reset()">重置</el-button>
    </el-form-item>
  </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="addDept" v-has="'dept-create'">新增</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="deptList"
        style="width: 100%"
        row-key="_id"
        :tree-props="{ children: 'children' }"
      >
      <h1>创建部门</h1>
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" min-width="100">
          <template #default="scope" >
            <el-button type="primary" @click="editDept(scope.row)"  v-has="'dept-edit'">编辑</el-button>
            <el-button
              type="danger"
             :disabled="scope.row.parentId[0]==null"
              @click="deleteItem(scope.row)"
               v-has="'dept-delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      
      <el-dialog
        v-model="dialogVisible"
        :title="action == 'create' ? '新建部门' : '修改部门'"
        @close="handleCancel"
      >
    
        <el-form :model="form" ref="dialogForm" :rules="rule">
            <el-form-item label="上级部门" label-width="100px" prop="parentId">
            <div class="example-block">
              <el-cascader
                :options="deptList"
                :props="{
                  checkStrictly: true,
                  value: '_id',
                  label: 'deptName',
                }"
                clearable
                style="with: 100%"
                placeholder="请选择部门"
                v-model="form.parentId"
              />
            </div>
          </el-form-item>

          <el-form-item label="部门名称" label-width="100px" prop="deptName">
            <el-input
              v-model="form.deptName"
              autocomplete="false"
            />
          </el-form-item>
          <el-form-item label="负责人" label-width="100px" prop="userId">
            <el-select v-model="form.userName"   placeholder="选择负责人" style="width:100%" @change="chooseEmail">
        <el-option  v-for="item in userList" 
        :key="item.userId"
        :label="item.userName"
         :value="item.userName"
        />
      </el-select>
          </el-form-item>
          <el-form-item label="负责人邮箱" label-width="100px" prop="userEmail">
            <el-input v-model="form.userEmail" autocomplete="false" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button type="primary" @click="handleSubmit(dialogForm)">
              确定
            </el-button>
            <el-button @click="dialogVisible = !dialogVisible">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, toRaw } from "vue";
import { ElMessage, formatter } from "element-plus";
import utils from "../utils/index.js";
import api from "../api/index.js";

//定义校验规则
const rule = reactive({
  deptId: {
    required: true,
    message: "请选择上级部门",
    trigger: "blur",
  },
  deptName: {
    required: true,
    message: "请输入部门名称",
    trigger: "blur",
  },
  userName: [
    {
     required: true,
      message: "请选择负责人",
      trigger: "blur",
    },
  ],
});
const action = ref("");
const loading = ref(true);
const dialogForm = ref(null);
const searchForm = ref(null);

const dialogVisible = ref(false);

const deptList = ref([]);
const userList = ref([]);

const total = ref(0);
//定义模块列表
const table = reactive({
  deptName: "",
});
const form=ref({})


//发送删除请求
const deleteData = async (data) => {
  let result;
  try {
    result = await api.delteSelect(data);
  } catch (error) {
    console.log(error.data);
    ElMessage.fail("删除失败，请稍后再试");
  }

  if (result.data.code == 200) {
    getUserList();

    ElMessage.success("删除成功");
  }
};

//动态定义表达格式
const columns = reactive([
  {
    label: "部门名称",
    prop: "deptName",
  },
  {
    label: "负责人",
    prop: "userName",
  },

  {
    label: "更新时间",
    prop: "updateTime",
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "创建时间",
    prop: "createTime",
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
]);

//请求用户数据
const getDepaList = async () => {
  getAllUser()
  getDeptData();
};



//请求部门列表方法
const getDeptData = async () => {
  loading.value = true;
  let result;
  console.log(toRaw(table));
  try {
    result = await api.getDeptList(toRaw(table));
  } catch (error) {
    console.log(error.data);
    let message = "请求失败";
    
    if (error.data.code == 40001) {
      message = error.data.msg;
    }
    let timer = setTimeout(() => {
      loading.value = false;
      ElMessage.error(message);
    }, 3000);
  }

  if (result.data.code == 200) {
    loading.value = false;
    deptList.value = result.data.data;
     ElMessage.success('请求数据成功');
    console.log(deptList.value);
  }
};
//请求用户列表方法
const getAllUser = async () => {
 
  let result;
  try {
    result = await api.getAllUser();
  } catch (error) {
    console.log(error.data);
 
  }

  if (result.data.code == 200) {
   
    userList.value = result.data.data;
    console.log(userList.value);
  }
};
//定义部门提交事件
const handleSubmit = (dialogForm) => {
  dialogForm.validate((valid) => {
    if (valid) {
      let data = toRaw(form.value);
      // data.updateTime=`ISODate(${new Date().toISOString()})`
      let item=userList.value.filter((ele)=>ele.userName==data.userName)  
      data.userId=item[0].userId
      data.action=action.value
      addDeptData(data)
      
    }
  });
};
//将修改的数据提交到后台
const addDeptData = async (data) => {
  
  let result;
  try {
    result = await api.deptOperate(data);
    form.value = {
    parentId:[null]
  };
  } catch (error) {
    
    console.log(error.data);
    let message = "修改失败";
   
    if (error.data.code == 40001) {
      message = error.data.msg;
    }
    let timer = setTimeout(() => {
     dialogVisible.value=false
      ElMessage.error(message);
    }, 3000);
  }

  if (result.data.code == 200) {
    
     dialogVisible.value=false
  ElMessage.success('修改成功');
  getDeptData()
  }
};
// 新建部门
const addDept=()=>{
  action.value='create'
   dialogVisible.value=!dialogVisible.value
}
//删除部门
const deleteItem=(row)=>{
    let data={
      action:'delete',
      _id:row._id
    }
addDeptData(data)
}
//修改部门
const editDept=(row)=>{
 action.value='edit'
 dialogVisible.value=!dialogVisible.value
 Object.assign( form.value,row )
 console.log(form.value);
 
}
//重置表单
const handleCancel = () => {
  dialogForm.value.resetFields();
 form.value={}
 
  getDeptData()
};
const reset=()=>{
  table.deptName=''
  searchForm.value.resetFields();
  getDeptData()
}
const chooseEmail=(val)=>{
    console.log(val);
    let item=userList.value.filter((ele)=>ele.userId==val)
    console.log(item);
    form.value.userEmail=item[0].userEmail
}
getDepaList();
</script>

<style lang="scss" scoped>
.query-from {
  width: 100%;
  background-color: white;
  .demo-form-inline {
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 60px;
    .el-form-item {
      margin: 0;
    }
  }
}
.base-table {
  overflow: hidden;
  .action {
    margin: 20px 20px;
  }
}

.user-managee {
  overflow: hidden;
}
.example-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
</style>
